<template>
  <div>
    <div v-if="!loading && formData.formItemList" class="form-index">
      <!-- 添加背景层 -->
      <div class="background-layer" :style="getBackgroundStyle"></div>
      <!-- 内容层 -->
      <div class="content-layer">
        <el-row>
          <el-col :xs="24" :sm="20" :md="18" :lg="14" :xl="12">
            <!-- 提交成功结果页 -->
            <div v-if="submitted" class="result-container">
              <el-result
                icon="success"
                :title="formData.publishSetting.submitText"
                :sub-title="formData.publishSetting.jumpInfo.description"
              >
                <template #extra>
                  <div v-if="formData.publishSetting.jumpInfo.link" class="countdown">
                    {{ countdown }}秒后{{
                      /^(https?|ftp):\/\//.test(formData.publishSetting.jumpInfo.link)
                        ? '跳转'
                        : '关闭页面'
                    }}
                  </div>
                </template>
              </el-result>
            </div>
  
            <!-- 表单内容 -->
            <div v-else class="form-container">
              <!-- 左侧导航 -->
              <div class="form-left" :class="{ collapsed: isNavCollapsed }">
                <el-affix :offset="20">
                  <div class="nav-container">
                    <div class="nav-header">
                      <div class="nav-title" v-show="!isNavCollapsed">题目导航</div>
                      <el-icon class="collapse-icon" @click="toggleNav">
                        <Fold v-if="!isNavCollapsed" />
                        <Expand v-else />
                      </el-icon>
                    </div>
                    <el-scrollbar v-show="!isNavCollapsed">
                      <div class="nav-list">
                        <div
                          v-for="question in displayQuestions.filter((q) => q.type !== 'pagenation')"
                          :key="question.formItemId"
                          class="nav-link"
                          :class="{
                            active: activeQuestionId === question.formItemId,
                            'is-title': question.type === 'secondTitle'
                          }"
                          @click="handleNavClick(question)"
                        >
                          <div class="nav-item">
                            <div class="nav-item-content">
                              <template v-if="question.type !== 'secondTitle'">
                                <span class="required-mark">{{ question.require ? '*' : '' }}</span>
                                <span class="nav-item-text">{{ getQuestionLabel(question) }}</span>
                              </template>
                              <template v-else>
                                <span class="nav-item-text title-text">{{ question.label }}</span>
                              </template>
                            </div>
                            <el-icon
                              v-if="question.type !== 'secondTitle'"
                              class="check-icon"
                              :class="{ 'is-answered': form[question.formItemId] }"
                            >
                              <CircleCheck />
                            </el-icon>
                          </div>
                        </div>
                      </div>
                    </el-scrollbar>
                  </div>
                </el-affix>
              </div>
              <!-- 中间内容 -->
              <div class="form-center">
                <!-- 移动端快捷操作 -->
                <div v-if="!callback" class="mobile-quick-actions">
                  <QuickActions :setting="formData.publishSetting" />
                </div>
                <!-- Logo -->
                <div v-if="formData.formAppearanceInfo.showLogo" class="form-logo">
                  <img :src="formData.formAppearanceInfo.logoImg" alt="logo" />
                </div>
                <!-- 表单头部 -->
                <div
                  v-if="formData.formAppearanceInfo.headerImg"
                  class="form-header"
                  :style="{
                    backgroundImage: `url(${formData.formAppearanceInfo.headerImg})`,
                    backgroundSize: 'cover',
                    backgroundPosition: 'center'
                  }"
                ></div>
                <!-- 表单标题 -->
                <h2 class="form-title">
                  {{ formData.label }}
                </h2>
                <!-- 表单描述 -->
                <div v-if="formData.description" class="form-description">
                  {{ formData.description }}
                </div>
                <!-- 表单来源 -->
                <div v-if="formData.publishSetting.showSourceName && formData.sourceId" class="form-source">
                  来源：{{ formData.sourceName }}
                </div>
                <!-- 分页信息 -->
                <el-divider v-if="formData.hasPageCmp">
                  <span class="form-page">第{{ currentPage }}页/共{{ totalPages }}页</span>
                </el-divider>
                <!-- 表单内容 -->
                <div class="form-content">
                  <el-form
                    ref="formRef"
                    :model="form"
                    :rules="formRules"
                    :validate-on-rule-change="false"
                    label-width="120px"
                  >
                    <!-- 当前页显示的题目 -->
                    <el-form-item
                      v-for="question in currentPageQuestions"
                      :key="question.formItemId"
                      :label="getQuestionLabel(question)"
                      :id="`${question.formItemId}`"
                      :prop="question.formItemId"
                      label-position="top"
                      v-show="currentPageQuestions.includes(question)"
                    >
                      <div
                        class="question-content"
                        :style="{ width: question.width ? question.width + 'px' : '100%' }"
                      >
                        <div v-if="question.description" class="question-description">
                          {{ question.description }}
                        </div>
                        <component
                          :is="getComponent(question.type)"
                          v-model:modelValue="form[question.formItemId]"
                          v-model:formRules="formRules"
                          :setting="question"
                        />
                      </div>
                    </el-form-item>
  
                    <!-- 其他页的题目（隐藏） -->
                    <el-form-item
                      v-for="question in displayQuestions.filter(
                        (q) => q.type !== 'pagenation' && !currentPageQuestions.includes(q)
                      )"
                      :key="question.formItemId"
                      :prop="question.formItemId"
                      style="display: none"
                    >
                      <component
                        :is="getComponent(question.type)"
                        v-model:modelValue="form[question.formItemId]"
                        v-model:formRules="formRules"
                        :setting="question"
                      />
                    </el-form-item>
                  </el-form>
                  <!-- 分页按钮 -->
                  <div v-if="formData.hasPageCmp" class="pagination-buttons">
                    <el-button v-if="currentPage > 1" @click="handlePrevPage"> 上一页 </el-button>
                    <el-button v-if="currentPage < totalPages" type="primary" @click="handleNextPage">
                      下一页
                    </el-button>
                    <template v-if="currentPage === totalPages">
                      <el-button @click="resetForm">重置</el-button>
                      <el-button
                        type="primary"
                        :loading="submitting"
                        :disabled="submitting"
                        @click="submitForm"
                      >
                        {{ submitting ? '提交中...' : '提交' }}
                      </el-button>
                    </template>
                  </div>
  
                  <!-- 无分页时的按钮 -->
                  <div v-else class="form-footer">
                    <el-button @click="resetForm">重置</el-button>
                    <el-button
                      type="primary"
                      :loading="submitting"
                      :disabled="submitting"
                      @click="submitForm"
                    >
                      {{ submitting ? '提交中...' : '提交' }}
                    </el-button>
                  </div>
                </div>
              </div>
              <!-- PC端快捷操作 -->
              <div v-if="!callback" class="form-right">
                <QuickActions :setting="formData.publishSetting" />
              </div>
            </div>
          </el-col>
        </el-row>
      </div>
    </div>
    <!-- 添加加载状态显示 -->
    <div v-else class="loading-container">
      <el-empty description="加载中..." />
    </div>
    <PaperHistory v-if="showPaperHistory" :formId="formData.id" @apply="handleApply" />
  </div>
</template>

<script setup>
/* eslint-disable */
import { ref, markRaw, computed, watch, nextTick, onMounted, onUnmounted } from 'vue'
import { useRouter } from 'vue-router'
import { getFormData, insertPaperResult } from '@/api/form'
import { CircleCheck, Expand, Fold } from '@element-plus/icons-vue'
import { ElMessage } from 'element-plus'
import { decrypt } from '@ruifox-cms/utils/src/crypto'
import { getToken, getUserInfo } from '@ruifox-cms/utils/src/storage'
import axios from 'axios'
import QuickActions from './components/QuickActions.vue'
import PaperHistory from './components/PaperHistory.vue'
import FormInput from './components/formItems/FormInput.vue'
import FormTextarea from './components/formItems/FormTextarea.vue'
import FormRadio from './components/formItems/FormRadio.vue'
import FormDate from './components/formItems/FormDate.vue'
import FormCheckbox from './components/formItems/FormCheckbox.vue'
import FormSelectSingle from './components/formItems/FormSelectSingle.vue'
import FormSelectMultiple from './components/formItems/FormSelectMultiple.vue'
import FormFileUpload from './components/formItems/FormFileUpload.vue'
import FormImgUpload from './components/formItems/FormImgUpload.vue'
import FormSecondTitle from './components/formItems/FormSecondTitle.vue'
import FormName from './components/formItems/FormName.vue'
import FormPhone from './components/formItems/FormPhone.vue'
import FormIdentity from './components/formItems/FormIdentity.vue'
import FormNative from './components/formItems/FormNative.vue'
import request from '@/utils/request'

const components = ref({
  input: markRaw(FormInput),
  textarea: markRaw(FormTextarea),
  radio: markRaw(FormRadio),
  date: markRaw(FormDate),
  checkbox: markRaw(FormCheckbox),
  selectSingle: markRaw(FormSelectSingle),
  selectMultiple: markRaw(FormSelectMultiple),
  fileUpload: markRaw(FormFileUpload),
  imgUpload: markRaw(FormImgUpload),
  secondTitle: markRaw(FormSecondTitle),
  baseInfo: markRaw(FormName),
  phone: markRaw(FormPhone),
  identity: markRaw(FormIdentity),
  native: markRaw(FormNative)
})
const getComponent = (type) => {
  return components.value[type] || null
}

const callback = computed(() => router.currentRoute.value.query.callback) // 有回调时，一般为上层业务调用，有自带的投递记录和个人中心，此时不展示快捷操作
const loading = ref(true)
const formRef = ref(null)
const formRules = ref({})
const form = ref({})
const formData = ref({
  formItemList: [],  // 添加初始值
  formAppearanceInfo: {},
  publishSetting: {
    jumpInfo: {}
  }
})

// 计算要显示的题目
const displayQuestions = computed(() => {
  const questions = formData.value.formItemList
  const result = []
  const connectedIds = new Set() // 存储所有被关联的题目ID
  const shouldShowConnected = new Set() // 存储当前应该显示的关联题目ID

  // 收集所有被关联的题目ID
  questions.forEach((question) => {
    if (question.connect) {
      question.default.forEach((option) => {
        if (option.connect?.length > 0) {
          option.connect.forEach((id) => connectedIds.add(id))
        }
      })
    }
  })

  // 收集当前应该显示的关联题目ID
  questions.forEach((question) => {
    if (question.connect && form.value[question.formItemId]) {
      const selectedOption = question.default.find(
        (opt) =>
          opt.label === form.value[question.formItemId] ||
          opt.placeholder === form.value[question.formItemId]
      )
      if (selectedOption && selectedOption.connect?.length > 0) {
        selectedOption.connect.forEach((id) => shouldShowConnected.add(id))
      }
    }
  })

  // 按原有顺序遍历题目
  questions.forEach((question) => {
    // 如果是分页，直接添加
    if (question.type === 'pagenation') {
      result.push(question)
      return
    }

    // 如果是被关联的题目，只有在应该显示时才添加
    if (connectedIds.has(question.formItemId)) {
      if (shouldShowConnected.has(question.formItemId)) {
        result.push(question)
      }
      return
    }

    // 添加非关联题目
    result.push(question)

    // 如果是一页一题模式且不是最后一个题目，添加分页
    if (
      formData.value.onePageOneQs &&
      formData.value.hasPageCmp &&
      questions.indexOf(question) < questions.length - 1
    ) {
      result.push({ type: 'pagenation' })
    }
  })

  return result
})

// 获取题目的实际显示标题（序号+label）
const getQuestionLabel = (question) => {
  if (question.type === 'pagenation' || question.type === 'secondTitle') return ''
  // 过滤掉分页器和二级标题，只计算实际题目的序号
  const realQuestions = displayQuestions.value.filter(
    (q) => q.type !== 'pagenation' && q.type !== 'secondTitle'
  )
  return `${realQuestions.indexOf(question) + 1}. ${question.label}`
}

// 监听表单值的变化，处理关联题目的答案清除
const previousValues = ref({})
watch(
  form,
  (newForm) => {
    formData.value.formItemList.forEach((question) => {
      if (question.connect) {
        const newValue = newForm[question.formItemId]
        const oldValue = previousValues.value[question.formItemId]

        if (newValue !== oldValue) {
          const oldOption = question.default.find(
            (opt) => opt.label === oldValue || opt.placeholder === oldValue
          )
          const newOption = question.default.find(
            (opt) => opt.label === newValue || opt.placeholder === newValue
          )

          const oldConnectedIds = oldOption?.connect || []
          const newConnectedIds = newOption?.connect || []

          oldConnectedIds.forEach((id) => {
            if (!newConnectedIds.includes(id)) {
              delete form.value[id]
            }
          })
        }
      }
      // 更新上一次的值
      previousValues.value[question.formItemId] = newForm[question.formItemId]
    })
  },
  { deep: true }
)

const resetForm = () => {
  form.value = {}
  currentPage.value = 1
}

const submitting = ref(false)
const submitted = ref(false)
const countdown = ref(0)

// 修改提交表单方法
const submitForm = async () => {
  if (submitting.value) return

  try {
    submitting.value = true
    const valid = await validateAll()
    if (valid) {
      // 这里处理表单提交逻辑
      const data = {
        formId: formData.value.id,
        sourceId: JSON.parse(localStorage.getItem('baseFormInfo')).sourceId,
        modelValue: form.value
      }
      const res = await insertPaperResult(data)

      if (res.code === 20000) {
        // 显示提交成功页面
        submitted.value = true
        await handleCallback(res.data.resultId)

        // 清理本地存储的表单信息
        localStorage.removeItem('baseFormInfo')

        // 如果需要跳转
        if (formData.value.publishSetting.jumpInfo.link) {
          // 开始倒计时
          countdown.value = formData.value.publishSetting.jumpInfo.autoTime
          const timer = setInterval(() => {
            countdown.value--
            if (countdown.value <= 0) {
              clearInterval(timer)
              // 判断跳转类型
              if (/^(https?|ftp):\/\//.test(formData.value.publishSetting.jumpInfo.link)) {
                window.location.href = formData.value.publishSetting.jumpInfo.link
              } else {
                window.close()
              }
            }
          }, 1000)
        }
      } else {
        submitting.value = false
        ElMessage.error(res.message || '提交失败')
      }
    } else {
      submitting.value = false
    }
  } catch (error) {
    submitting.value = false
    ElMessage.error('提交失败，请重试')
  }
}

// 表单提交回调
const handleCallback = async (id) => {
  const callback = router.currentRoute.value.query.callback
  if (callback) {
    const callbackData = decrypt(callback)
    request.post(
      callbackData.callbackUrl,
      {
        paperResultId: id,
        ...callbackData.data
      },
      {
        baseURL:  process.env.NODE_ENV == 'development' ? '/recruitment_api' : '/api',
        headers: {
          'userId': getUserInfo() ? getUserInfo().id : null,
          'X-token': getToken() ? getToken() : '',
          'Content-Type': 'application/json',
          'X-Timestamp': Date.now()
        }
      }
    )
  }
}

// 添加分页相关状态
const currentPage = ref(1)

// 计算分页后的题目组
const questionGroups = computed(() => {
  if (!formData.value.hasPageCmp) {
    return [displayQuestions.value]
  }

  const groups = []
  let currentGroup = []
  displayQuestions.value.forEach((question) => {
    if (question.type === 'pagenation') {
      if (currentGroup.length > 0) {
        groups.push(currentGroup)
        currentGroup = []
      }
    } else {
      currentGroup.push(question)
    }
  })

  if (currentGroup.length > 0) {
    groups.push(currentGroup)
  }

  return groups
})

// 当前页显示的题目
const currentPageQuestions = computed(() => {
  return questionGroups.value[currentPage.value - 1] || []
})

// 总页数
const totalPages = computed(() => questionGroups.value.length)

// 处理页面切换
const handlePrevPage = () => {
  if (currentPage.value > 1) {
    currentPage.value--
  }
}

const handleNextPage = () => {
  if (currentPage.value < totalPages.value) {
    currentPage.value++
  }
}

// 添加当前活跃题目的 ref
const activeQuestionId = ref('')

// 添加监听滚动的函数
const updateActiveQuestion = () => {
  if (!currentPageQuestions.value.length) return

  const questions = currentPageQuestions.value
  for (const question of questions) {
    const element = document.getElementById(question.formItemId)
    if (element) {
      const rect = element.getBoundingClientRect()
      // 当题目进入视口的上半部分时，将其设为活跃
      if (rect.top <= window.innerHeight / 2 && rect.bottom >= window.innerHeight / 2) {
        activeQuestionId.value = question.formItemId
        break
      }
    }
  }
}

// 在页面切换时更新活跃题目
watch(currentPage, () => {
  nextTick(() => {
    if (currentPageQuestions.value.length) {
      activeQuestionId.value = currentPageQuestions.value[0].formItemId
    }
  })
})

// 在组件挂载时添加滚动监听
onMounted(() => {
  if (currentPageQuestions.value.length) {
    activeQuestionId.value = currentPageQuestions.value[0].formItemId
  }
  window.addEventListener('scroll', updateActiveQuestion)
})

// 在组件卸载时移除滚动监听
onUnmounted(() => {
  window.removeEventListener('scroll', updateActiveQuestion)
})

// 修改 handleNavClick 函数
const handleNavClick = (question) => {
  const pageIndex = questionGroups.value.findIndex((group) =>
    group.some((q) => q.formItemId === question.formItemId)
  )

  if (pageIndex !== -1) {
    currentPage.value = pageIndex + 1
    nextTick(() => {
      const element = document.getElementById(question.formItemId)
      if (element) {
        element.scrollIntoView({ behavior: 'smooth' })
        activeQuestionId.value = question.formItemId
      }
    })
  }
}

// 添加导航栏展开/收起的功能
const isNavCollapsed = ref(false)
const toggleNav = () => {
  isNavCollapsed.value = !isNavCollapsed.value
}

// 计算背景样式
const getBackgroundStyle = computed(() => {
  const { backgroundType, backgroundColor, backgroundImg } =
    formData.value.formAppearanceInfo
  if (backgroundType === 'img' && backgroundImg) {
    return {
      background: `url(${backgroundImg}) center/cover no-repeat fixed`,
      filter: 'blur(3px)',
      position: 'fixed',
      top: 0,
      left: 0,
      right: 0,
      bottom: 0,
      zIndex: -1
    }
  }
  return {
    background: backgroundColor || '#f6f6f6'
  }
})

// 获取主题色
const themeColor = computed(() => formData.value.formAppearanceInfo.themeColor || '#409EFF')

// 动态设置主题色
watch(
  themeColor,
  (newColor) => {
    if (newColor) {
      const style = document.createElement('style')
      style.innerHTML = `
        :root {
          --el-color-primary: ${newColor} !important;
        }
      `
      document.head.appendChild(style)
    }
  },
  { immediate: true }
)

// 手动验证所有显示的题目
const validateAll = async () => {
  let isValid = true
  let firstErrorQuestion = null
  let hasCurrentPageError = false

  // 先验证当前页的题目
  for (const question of currentPageQuestions.value) {
    try {
      await formRef.value.validateField(question.formItemId)
    } catch (error) {
      isValid = false
      hasCurrentPageError = true
      firstErrorQuestion = firstErrorQuestion || question
    }
  }

  // 如果当前页没有错误，再验证其他页的题目
  if (!hasCurrentPageError) {
    const otherQuestions = displayQuestions.value.filter(
      (q) => q.type !== 'pagenation' && !currentPageQuestions.value.includes(q)
    )

    for (const question of otherQuestions) {
      try {
        await formRef.value.validateField(question.formItemId)
      } catch (error) {
        isValid = false
        firstErrorQuestion = firstErrorQuestion || question
      }
    }

    if (!isValid) {
      ElMessage.error('请检查表单填写是否正确')
      // 跳转到第一个错误题目所在页
      handleNavClick(firstErrorQuestion)
      // 等待页面更新后再次触发验证，显示错误信息
      nextTick(() => {
        formRef.value.validateField(firstErrorQuestion.formItemId)
      })
    }
  }

  return isValid
}

const router = useRouter()
const showPaperHistory = ref(false) // 当前表单填写记录
// 检查基础信息并获取表单数据
const initForm = async () => {
  loading.value = true
  try {
    // 获取本地存储的基础信息
    const baseFormInfo = localStorage.getItem('baseFormInfo')
    if (!baseFormInfo) {
      router.replace({
        path: '/404',
        query: { message: '无法访问表单，请从正确的入口访问',callback:callback.value }
      })
      return
    }

    // 解析基础信息
    const baseInfo = JSON.parse(baseFormInfo)
    // 获取表单数据
    const res = await getFormData({
      form: baseInfo.formId,
      sourceId: baseInfo.sourceId
    })

    if (res.code === 20000) {
      formData.value = res.data

      // 登录了的话展示当前表单的填写记录
      if (!getToken()) return
      showPaperHistory.value = true
    } else {
      router.replace({
        path: '/404',
        query: { message: '获取表单数据失败' }
      })
    }
  } catch (error) {
    router.replace({
      path: '/404',
      query: { message: '获取表单数据失败，请联系管理员' }
    })
  } finally {
    loading.value = false
    nextTick(() => {
      sendHeightToParent()
    })
  }
}

// 表单历史详情
const handleApply = (data) => {
  Object.assign(form.value, data)
}

// 添加发送高度到父窗口的方法
const sendHeightToParent = () => {
  // 检查是否在 iframe 中
  if (window !== window.parent) {
    const height = document.documentElement.scrollHeight || document.body.scrollHeight
    window.parent.postMessage({
      type: 'form-setHeight',
      height: height
    }, '*')
  }
}

onMounted(() => {
  initForm()
  window.addEventListener('resize', sendHeightToParent)
})

onUnmounted(() => {
  window.removeEventListener('resize', sendHeightToParent)
})
</script>

<style lang="scss" scoped>
.form-index {
  min-height: 100vh;
  padding: 20px;
  box-sizing: border-box;
  position: relative;

  .background-layer {
    position: fixed;
    top: 0;
    left: 0;
    right: 0;
    bottom: 0;
    z-index: -1;
  }

  .content-layer {
    position: relative;
    z-index: 1;
  }

  .el-row {
    display: flex;
    justify-content: center;
    height: 100%;
    margin: 0 auto;
  }

  .form-container {
    display: flex;
    gap: 20px;
    width: 100%;

    .form-left {
      width: 220px;
      flex-shrink: 0;
      transition: width 0.3s ease-in-out;

      &.collapsed {
        width: 50px;

        .nav-container {
          .nav-header {
            padding: 16px 0;
            justify-content: center;

            .collapse-icon {
              margin: 0;
            }
          }
        }
      }

      .nav-container {
        background: #fff;
        border-radius: 8px;
        box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.1);
        transition: all 0.3s ease-in-out;

        .nav-header {
          padding: 16px;
          display: flex;
          align-items: center;
          justify-content: space-between;

          .nav-title {
            font-size: 16px;
            font-weight: bold;
            white-space: nowrap;
          }

          .collapse-icon {
            cursor: pointer;
            font-size: 18px;
            margin-left: 8px;
            color: #909399;
            transition: transform 0.3s ease-in-out;

            &:hover {
              color: v-bind('themeColor');
            }
          }
        }

        .nav-list {
          .nav-link {
            cursor: pointer;
            padding: 8px 16px;

            &:hover {
              background-color: #f5f7fa;
            }

            &.active {
              background-color: #f5f7fa;

              .nav-item {
                color: v-bind('themeColor');
              }
            }

            .nav-item {
              display: flex;
              align-items: center;
              justify-content: space-between;
              font-size: 14px;
              color: #606266;

              .nav-item-content {
                flex: 1;
                min-width: 0;
                display: flex;
                align-items: center;

                .required-mark {
                  flex-shrink: 0;
                  display: inline-block;
                  width: 8px;
                  color: #f56c6c;
                }

                .nav-item-text {
                  overflow: hidden;
                  text-overflow: ellipsis;
                  white-space: nowrap;
                  margin-right: 8px;
                }
              }

              .check-icon {
                flex-shrink: 0;
                font-size: 16px;
                color: #dcdfe6;
                margin-left: 4px;

                &.is-answered {
                  color: #67c23a;
                }
              }
            }

            &.is-title {
              .nav-item {
                .nav-item-content {
                  .title-text {
                    color: #303133;
                    font-weight: bold;
                    font-size: 14px;
                  }
                }
              }

              &:hover {
                background-color: transparent;
                cursor: default;
              }

              &.active {
                background-color: transparent;
              }
            }
          }
        }

        :deep(.el-scrollbar) {
          height: calc(100vh - 100px);
        }
      }
    }

    .form-center {
      flex: 1;
      background: #fff;
      border-radius: 8px;
      box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.1);
      overflow: hidden;

      .mobile-quick-actions {
        display: none;
        padding: 12px 16px;
        background: #fff;
        border-bottom: 1px solid #eee;
        position: sticky;
        top: 0;
        z-index: 10;

        :deep(.quick-actions) {
          flex-direction: row;
          justify-content: space-around;
        }
      }
      
      .form-logo {
        height: 50px;
        display: flex;
        align-items: center;
        justify-content: center;
        padding: 10px;
        background: #fff;

        img {
          height: 100%;
          object-fit: contain;
        }
      }

      .form-header {
        height: 200px;
        background: #ccc;
        transition: background-image 0.3s;
      }

      .form-title,
      .form-description {
        padding: 0 100px;
        margin: 20px 0 0;
        text-align: center;
        color: #333;
        font-weight: 600;
        font-size: 28px;
        word-break: break-all;
        white-space: pre-wrap;
      }

      .form-description {
        margin-top: 10px;
        font-size: 14px;
        font-weight: 400;
        color: #606266;
      }

      .form-source {
        margin: 20px 0 30px;
        text-align: center;
        font-size: 14px;
        color: #606266;
      }

      .form-page {
        font-size: 16px;
        font-weight: bold;
      }

      .form-content {
        padding: 20px 50px;

        .el-form {
          max-width: 800px;
          margin: 0 auto;

          .el-form-item {
            scroll-margin-top: 20px; // 为锚点滚动预留空间
            margin-bottom: 30px;

            .question-content {
              padding-left: 21px;
              box-sizing: border-box;

              .question-description {
                margin-bottom: 10px;
                line-height: 14px;
                font-size: 14px;
                color: #606266;
              }
            }

            ::v-deep .el-form-item__error {
              margin-top: 5px;
              padding-left: 21px;
            }
          }
          ::v-deep .el-form-item:not(.is-required) .el-form-item__label {
            margin-left: 21px;
          }
        }
      }

      .form-footer {
        display: flex;
        justify-content: center;
        margin: 50px auto;
      }
    }

    .form-right {
      width: 40px;
      flex-shrink: 0;
    }
  }
}

// 响应式调整
@media screen and (max-width: 1440px) {
  .form-index .form-container .form-center .form-content {
    padding: 50px 20px !important;
  }
}
@media screen and (max-width: 768px) {
  .form-index {
    padding: 0;
    .form-container {
      .form-left {
        display: none;
      }
      .form-center {
        .mobile-quick-actions {
          display: block !important;
          margin-bottom: 20px;
        }
        .form-content {
          padding: 20px;
        }
        
        // 调整其他元素的上边距，避免被固定定位的快捷操作遮挡
        .form-logo,
        .form-header,
        .form-title {
          margin-top: 0;
        }
      }
      .form-right {
        display: none; // 移动端隐藏
      }
    }
  }
}

::v-deep .el-form .el-form-item .el-form-item__label {
  font-size: 16px;
  font-weight: bold;
}

.pagination-buttons {
  display: flex;
  justify-content: center;
  gap: 16px;
  margin-top: 20px;
}

.nav-container {
  :deep(.el-anchor-link) {
    &.active {
      // 移除默认的高亮样式
      &::before {
        display: none;
      }
    }

    // 自定义高亮样式
    &.active .nav-item {
      background-color: #f5f7fa;
    }

    .nav-item {
      border-radius: 4px;
      transition: background-color 0.3s;
    }
  }
}

.result-container {
  background: #fff;
  border-radius: 8px;
  box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.1);
  padding: 40px;
  text-align: center;
  min-height: 60vh;
  display: flex;
  align-items: center;
  justify-content: center;

  :deep(.el-result) {
    width: 100%;

    .el-result__title {
      margin-top: 20px;
      font-size: 24px;
      color: #303133;
    }

    .el-result__subtitle {
      margin-top: 10px;
      font-size: 14px;
      color: #606266;
    }

    .countdown {
      margin-top: 20px;
      color: #909399;
      font-size: 14px;
    }
  }
}

.loading-container {
  min-height: 100vh;
  display: flex;
  align-items: center;
  justify-content: center;
  background-color: #f5f7fa;
}
</style>
